import { SerialPort, SerialPortOpenOptions } from 'serialport'

let temp = 2

interface PortInfo {
  path: string
  manufacturer: string | undefined
  serialNumber: string | undefined
  pnpId: string | undefined
  locationId: string | undefined
  productId: string | undefined
  vendorId: string | undefined
}

type ListenerType = 'close' | 'data' | 'end' | 'error' | 'pause' | 'readable' | 'resume'

const obj = {
  temp: 2
}
export class SerialPortWrapper {
  serialport: SerialPort | null = null
  timeOutTimer: NodeJS.Timeout | null = null
  timeOut: number = 3 * 1000

  temp = 2

  // 获取串口列表
  list() {
    return new Promise<PortInfo[]>((resolve, reject) => {
      SerialPort.list()
        .then((ports) => {
          resolve(ports)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  // 打开串口
  open(options: SerialPortOpenOptions<any>): Promise<SerialPort> {
    return new Promise((resolve, reject) => {
      this.serialport = new SerialPort(options, (err) => {
        if (err) return reject(err)
        resolve(this.serialport!)
      })
    })
  }

  // 关闭串口
  close() {
    return new Promise((resolve, reject) => {
      this.serialport?.close((err) => {
        if (err) return reject(err)
        resolve(true)
      })
    })
  }

  // 监听串口
  on(event: ListenerType, callback: (data: Buffer) => void) {
    // let fn = (data: Buffer) => {
    //   clearTimeout(this.timeOutTimer!)
    //   callback(data)
    // }
    this.serialport?.on(event, callback)
  }

  // 写入串口数据
  write(data: string | Buffer, encoding: BufferEncoding = 'utf8', callback?: (reject: (reason?: any) => void) => void) {
    return new Promise((resolve, reject) => {
      this.serialport?.write(data, encoding, (err) => {
        if (err) return reject(err)
        // this.timeOutTimer = setTimeout(() => {
        //   console.error(`接受 ${data} 指令响应超时`)
        //   return reject(`接收 ${data} 指令响应超时`)
        // }, this.timeOut)
        // console.log('2')
        callback && callback(reject)
        resolve(true)
      })
    })
  }
}

export const serialport = new SerialPortWrapper()

export const useSerialport = () => {
  const isLoading = ref(false)
  const isOpen = ref(false)
  const serialportList = ref<PortInfo[]>([])

  // 获取串口列表
  async function getSerialportList() {
    serialportList.value = await serialport.list()
  }

  // 打开串口
  async function open(options: SerialPortOpenOptions<any>) {
    try {
      await serialport.open(options)
      isOpen.value = true
    } catch (err) {
      console.error('打开串口失败：', err)
      isOpen.value = false
    }
  }

  // 关闭串口
  async function close() {
    try {
      await serialport.close()
      isOpen.value = false
    } catch (err) {
      isOpen.value = true
      console.error('关闭串口失败：', err)
    }
  }

  async function write(data: string | Buffer) {
    try {
      await serialport.write(data)
    } catch (err) {
      console.error('写入数据失败：', err)
    }
  }

  function on(event: ListenerType = 'data', callback: () => void) {
    serialport.on('data', callback)
  }

  return { isLoading, isOpen, serialportList, open, close }
}
